package com.hwh.traffic.fragment;


import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hwh.traffic.R;
import com.hwh.traffic.utils.HttpUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.app.Activity.RESULT_OK;


public class MyFragment extends Fragment {


    private static final int PERMISSION_UP_APK = 7854;
    private TextView mTitleText;
    private LinearLayout mLinearLayoutUpdate;
    private String version;
    private String saveDir;
    private File apkdir;
    private File apk;
    private ProgressBar pb_download;
    private MyHandler myHandler = new MyHandler();
    private TextView download_text;
    private boolean isClick = false;
    private String newVersion;
    private LinearLayout saysomething;
    private Button sentBtn;


    public class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code = msg.what;//接受处理码
            pb_download.setProgress(code);//给进度条的当前进度赋值
            download_text.setText("正在下载中,请不要离开此页面-" + code + "%");
            if (code == 100) {
                download_text.setText("下载完成");
            }
        }
    }


    public MyFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        AlertDialog alertDialog = builder.create();
        View view = View.inflate(getActivity(), R.layout.layout_input_dialog, null);
        alertDialog.setView(view);
        EditText editText = view.findViewById(R.id.et);
        sentBtn = view.findViewById(R.id.btn_send);
        sentBtn.setOnClickListener(v -> {
            //发送
            new Thread(() -> {
                try {
                    String opoinion = editText.getText().toString();
                    String version = getVersionName();
                    HttpUtil.httpPost("http://139.224.192.113:8081/opinion", "version=" + version + "&opoinion=" + opoinion);

                } catch (InterruptedException e) {

                    //e.printStackTrace();
                }finally {
                    getActivity().runOnUiThread(()->{
                        alertDialog.dismiss();
                        Toast.makeText(getActivity(),"提交建议成功",Toast.LENGTH_SHORT).show();
                    });
                }
            }).start();

        });


        mTitleText = getView().findViewById(R.id.text_title);
        mTitleText.setText("我的");
        pb_download = getView().findViewById(R.id.pb_download);
        download_text = getView().findViewById(R.id.download_text);

        TextView vv = getView().findViewById(R.id.version);
        vv.setText(getVersionName());
        saysomething = getView().findViewById(R.id.saysomething);
        saysomething.setOnClickListener(v -> {
            alertDialog.show();
        });

        mLinearLayoutUpdate = getView().findViewById(R.id.update);
        mLinearLayoutUpdate.setOnClickListener(v -> {
            if (isClick) {
                return;
            }
            isClick = true;
            version = getVersionName();
            //更新
            System.out.println("版本号" + getVersionName());
            String version = getVersionName();
            new Thread(() -> {
                newVersion = HttpUtil.httpGet("http://139.224.192.113:8081/version");
                if (!version.equals(newVersion) && newVersion != null) {
                    //更新
                    getActivity().runOnUiThread(() -> showUpdateDialog(newVersion));
                } else if (newVersion == null) {
                    Toast.makeText(getActivity(), "网络异常", Toast.LENGTH_SHORT).show();
                } else {
                    //已经是最新版本了
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getActivity(), "当前版本是最新版本", Toast.LENGTH_SHORT).show();
                    });
                }
            }).start();

        });

    }

    public String getVersionName() {
        //1.包的管理者，获取应用程序中清单文件中信息
        PackageManager packageManager = getActivity().getPackageManager();
        try {

            //getPackageName() : 获取应用程序的包名
            PackageInfo packageInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
            //获取应用程序版本号名称
            String versionName = packageInfo.versionName;
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            //找不到包名的异常
            e.printStackTrace();
            return null;
        }
    }

    protected void showUpdateDialog(String newVersion) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //设置标题
        builder.setTitle("新版本:" + newVersion);
        //设置图标
        //builder.setIcon(R.drawable.ic_launcher);
        //设置描述信息
        builder.setMessage("新版本上线了，快来下载吧!!!!");
        //设置升级按钮
        builder.setPositiveButton("升级", (dialog, which) -> {
            System.out.println("升级");
            download();
        });
        //设置取消按钮
        builder.setNegativeButton("取消", (dialog, which) -> System.out.println("取消"));
        //显示对话框
        builder.create().show();

    }

    protected void download() {
        if (Build.VERSION.SDK_INT < 29) {
            saveDir = Environment.getExternalStorageDirectory() +
                    "/fafubusapk/";
            apkdir = new File(saveDir);

        }
        //兼容 Android 10.0
        if (Build.VERSION.SDK_INT == 29) {
            saveDir = getActivity().getExternalFilesDir(null) +
                    "/fafubusapk/";
            apkdir = new File(saveDir);
        }
        if (!apkdir.exists()) {
            apkdir.mkdir();
        }
        try {
            apk = new File(apkdir + "/fafubus.apk");
            if (!apk.exists()) {
                apk.createNewFile();

            }
            new Thread(() -> {
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(apk, false);
                    getActivity().runOnUiThread(() -> Toast.makeText(getActivity(), "开始下载", Toast.LENGTH_LONG).show());
                    HttpUtil.download("http://139.224.192.113:8081/apk/fafubus-" + newVersion + ".apk", fos, myHandler);
                    installAPKWithHightSDK(apk);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    protected void install(File apk) {
        Uri uri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".fileProvider", apk);
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
        System.out.println("开始安装");
        getActivity().startActivity(install);
    }


    //8.0安装新版本APK权限
    private void peimissionO() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean b = getActivity().getPackageManager().canRequestPackageInstalls(); //检测是否允许安装apk
            if (b) {
                //安装apk
                install(apk);
            } else {
                //请求安装权限
                String[] permission = {Manifest.permission.REQUEST_INSTALL_PACKAGES};
                ActivityCompat.requestPermissions(getActivity(), permission, PERMISSION_UP_APK);
                Uri packageURI = Uri.parse("package:" + getActivity().getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                startActivityForResult(intent, 10086);

            }
        }
    }

    //权限
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_UP_APK:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //安装APK
                    install(apk);

                } else {
                    //跳转到安装未知应用界面
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, 7855);//on line 380
                }
                break;
        }
    }

    // 更换新的APK(android版本低于8.0)
    public void installAPKWithHightSDK(File file) {
        //跳转安装
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//  8.0
            peimissionO();//检查安装权限
        } else {
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {//  7.0
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri contentUri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".fileProvider", file);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {//7.0以下
                Intent install = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            }
            getActivity().startActivity(intent);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 10086) {
            //返回权限后，执行自己的逻辑；
            System.out.println("申请权限");
            install(apk);
        }
    }


}
